<template>
    <div class="search">
        <van-nav-bar title="商品搜索" left-arrow @click-left="$router.push('/')" />
        <van-search v-model="search" show-action placeholder="请输入搜索商品" @search="onSearch" ref="searchIpt">
            <template #action>
                <div @click="onSearch(search)">搜索</div>
            </template>
        </van-search>
        <div class="search_close">
            <span>最近搜索</span>
            <van-icon name="delete-o" @click="clear"></van-icon>
        </div>
        <div class="hisList">
            <div v-for="v in his" :key="v" @click="onSearch(v)">{{ v }}</div>
        </div>
    </div>
</template>

<script>
import { setHistory, getHistory } from '@/localStorage/search'
export default {
    name: 'Search',
    data() {
        return {
            search: '',//输入框的值
            his: getHistory()
        }
    },
    methods: {
        onSearch(keywords) {
            if (keywords === '') {
                this.$toast('搜索内容不能为空')
                return
            }
            // 添加历史 1若之前没有相关的搜索关键字,则追加到最前面 2若有相关关键字，则先删除在追加
            const index = this.his.indexOf(keywords)
            if (index !== -1) {
                // 说明有相同的关键字 先删除
                this.his.splice(index, 1)
            }
            this.his.unshift(keywords)

            // 每次追加都要持久化
            setHistory(this.his)

            // 跳转到搜索列表页
            this.$router.push(`/search/list?search=${keywords}`)
        },
        clear() {
            // 清空搜索列表
            this.his = []
            setHistory([])
        }
    },
    mounted() {
        // 一进页面就自动获取焦点
        this.$nextTick(() => {
            this.$refs.searchIpt.querySelector('input').focus()
        })
    },

}
</script>

<style lang="less" scoped>
.search {
    .hisList {
        display: flex;
        flex-wrap: wrap;
        padding: 10px;

        div {
            background-color: #f4f4f4;
            padding: 5px;
            border-radius: 1px;
            margin: 10px;
        }
    }

    .search_close {
        display: flex;
        justify-content: space-between;
        padding: 10px;
        align-items: center;
    }

}
</style>